package com.uinnova.product.eam.service.impl;

import com.uinnova.product.eam.dao.ChangeAssigneeRecordDao;
import com.uinnova.product.eam.feign.workable.entity.TaskRequest;
import com.uinnova.product.eam.feign.workable.entity.TaskResponse;
import com.uinnova.product.eam.model.es.ChangeAssigneeRecord;
import com.uinnova.product.eam.service.ChangeAssigneeRecordService;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
public class ChangeAssigneeRecordServiceImpl implements ChangeAssigneeRecordService {

    @Autowired
    private ChangeAssigneeRecordDao changeAssigneeRecordDao;

    @Override
    public Long addRecord(TaskRequest request, TaskResponse taskResponse) {
        ChangeAssigneeRecord record = new ChangeAssigneeRecord();
        record.setId(ESUtil.getUUID());
        record.setProcessInstanceId(taskResponse.getProcessInstanceId());
        record.setTaskId(taskResponse.getTaskId());
        record.setOrignAssignee(taskResponse.getUserId());
        record.setNowAssignee(request.getUserId());
        record.setOperator(SysUtil.getCurrentUserInfo().getLoginCode());
        record.setOperateTime(ESUtil.getNumberDateTime());
        changeAssigneeRecordDao.saveOrUpdate(record);
        return record.getId();
    }

    @Override
    public Long addRecordByUserId(String userId, TaskResponse taskResponse, String remarks) {
        ChangeAssigneeRecord record = new ChangeAssigneeRecord();
        record.setId(ESUtil.getUUID());
        record.setProcessInstanceId(taskResponse.getProcessInstanceId());
        record.setTaskId(taskResponse.getTaskId());
        record.setOrignAssignee(taskResponse.getUserId());
        record.setNowAssignee(userId);
        record.setOperator(SysUtil.getCurrentUserInfo().getLoginCode());
        record.setOperateTime(ESUtil.getNumberDateTime());
        if (StringUtils.isNotBlank(remarks)) {
            record.setRemarks(remarks);
        }
        changeAssigneeRecordDao.saveOrUpdate(record);
        return record.getId();
    }

    @Override
    public void deleteById(Long id) {
        changeAssigneeRecordDao.deleteById(id);
    }

    @Override
    public List<ChangeAssigneeRecord> queryByProcessInstanceId(String processInstanceId) {
        TermQueryBuilder query = QueryBuilders.termQuery("processInstanceId.keyword", processInstanceId);
        List<ChangeAssigneeRecord> records = changeAssigneeRecordDao.getListByQueryScroll(query);
        records.sort(Comparator.comparing(ChangeAssigneeRecord::getOperateTime));
        return records;
    }
}
